
package com.bjc.loginController;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bjc.base.bean.ResultVO;
import com.bjc.base.core.MyException;
import com.bjc.base.http.HttpAPIService;
import com.bjc.base.utils.StringUtil;
import com.bjc.core.bean.request.EmployeeReqVO;
import com.bjc.core.bean.request.RolePermissionReqVO;
import com.bjc.core.bean.request.UserRoleReqVO;
import com.bjc.core.bean.response.EmployeeVO;
import com.bjc.core.bean.response.RolePermissionVO;
import com.bjc.core.bean.response.UserRoleVO;
import com.bjc.core.service.IEmployeeService;
import com.bjc.core.service.IRolePermissionService;
import com.bjc.core.service.IUserRoleService;
import com.bjc.core.tool.service.IRedisService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @author zhengwei
 * @date 2017年7月17日
 */
@RestController
@RequestMapping("api/UserLogin")
@Api(value = "user-api", tags = { "用户登录模块" })
public class UserLoginController {

	// @Autowired
	// private IUserLoginService userService;

	@Autowired
	private IEmployeeService employeeService;

	@Autowired
	private IUserRoleService userRoleService;

	@Autowired
	private IRolePermissionService rolePermissionService;

	@Autowired
	private HttpAPIService httpAPIService;

	@Autowired
	private IRedisService iRedisService;

	@Value("${spring.sso.url}")
	private String url;

	/**
	 * 获取用户登录信息
	 * 
	 * @return UserBean
	 * @throws UnsupportedEncodingException
	 */
	@ApiOperation("获取用户登录信息")
	@GetMapping("getUserBeanInfo")
	public ResultVO getUserBeanInfo(HttpServletRequest request) throws UnsupportedEncodingException {
		ResultVO rtn = new ResultVO();
		rtn.setCode(400);
		rtn.setMessage("获取用户信息失败");
		String token = URLDecoder.decode(request.getHeader("bjcToken"), "UTF-8");
		// 将用户数据存入redis
		EmployeeVO employee2 = new EmployeeVO();
		iRedisService.setex(employee2.getWorkId(), 36000, JSON.toJSONString(employee2));
		Map<String, Object> query = new HashMap<String, Object>();
		long state = System.currentTimeMillis();
		query.put("ContextID", state + "");
		query.put("Data", token);
		String wxpost = httpAPIService.doWxPost(url, query);
		JSONObject obj = new JSONObject();
		obj = JSONObject.parseObject(wxpost);
		if (obj != null) {
			JSONObject date = obj.getJSONObject("Data");
			if (date != null) {
				JSONObject identity = date.getJSONObject("Identity");
				String username = identity.getString("LoginName");
				String workId = identity.getString("GlobalID");
				// 默认走ldap 验证，取值为空则为数据库验证
				String flag = "ldap";
				if (StringUtil.isNullOrEmpty(workId)) {
					if (username.startsWith("B-")) {
						workId = username;
					}
				}

				if (!StringUtil.isNullOrEmpty(workId)) {
					// 根据workId获取用户
					EmployeeReqVO employeeReqVO = new EmployeeReqVO();
					employeeReqVO.setWorkId(workId);
					EmployeeVO employee = employeeService.get(employeeReqVO);
					String emplName = null;
					if (employee != null) {
						emplName = employee.getEmployeeName();
					}

					if (StringUtil.equals(flag, "db")) {
						employee = new EmployeeVO();
						employee.setWorkId(workId);
						employee.setEmployeeName(emplName);
					}
					if (employee != null) {
						// 根据workId获取该用户的角色
						UserRoleReqVO userRoleReqVO = new UserRoleReqVO();
						userRoleReqVO.setWorkId(employee.getWorkId());
						List<UserRoleVO> roleList = userRoleService.getList(userRoleReqVO);
						StringBuffer sb = new StringBuffer();
						List<Integer> roleIdsArray = new ArrayList<>();
						for (UserRoleVO userRoleVO : roleList) {
							roleIdsArray.add(userRoleVO.getRoleId());
							sb.append(userRoleVO.getRoleKey()).append(",");
						}
						if (sb.length() > 1) {
							String roles = sb.substring(0, sb.length() - 1);
							employee.setRoles(roles);
						}

						// 根据用户角色获取权限
						Integer[] roleIds = roleIdsArray.toArray(new Integer[roleIdsArray.size()]);
						RolePermissionReqVO rpRepVO = new RolePermissionReqVO();
						rpRepVO.setRoleIds(roleIds);
						List<RolePermissionVO> rpVOList = rolePermissionService.getList(rpRepVO);
						StringBuffer sbRP = new StringBuffer();
						rpVOList.forEach(s -> {
							sbRP.append(s.getPermissionCode()).append(",");
						});
						employee.setPermissionCodes(sbRP.toString());

						rtn.setCode(200);
						rtn.setData(employee);
						rtn.setMessage("获取用户信息成功");

						// 将用户数据存入redis
						iRedisService.setex(token, 36000, JSON.toJSONString(employee));
					} else {
						rtn.setCode(50008);
//						rtn.setMessage("数据库中暂无此人");
					}
				} else {
					rtn.setCode(50008);
//					rtn.setMessage("数据库中暂无此人");
				}

			} else {
				rtn.setCode(50008);
				rtn.setData(null);
			}

		}
		return rtn;
	}

	/*
	 * 获取登录人的用户信息
	 */
	public EmployeeVO getEmployeeVO() {

		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		String bjcToken = request.getHeader("bjcToken");
		if (StringUtils.isEmpty(bjcToken)) {
			throw new MyException("bjcToken不能为空");
		}
		String bjcTokens = "";
		try {
			bjcTokens = URLDecoder.decode(bjcToken, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String user = iRedisService.get(bjcTokens);
		EmployeeVO employeeVO = null;
		if (StringUtils.isNotEmpty(user)) {
			employeeVO = JSON.parseObject(user, EmployeeVO.class);
		}
		return employeeVO;
	}

}
